// 引入内置词书数据
const { getBuiltinBooks, clearCache } = require('../../../utils/builtinBooks.js');

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    modalAnimation: {
      type: Object,
      value: null
    }
  },
  data: {
    builtinBooks: [],
    originalBooks: [], // 存储原始词书数据，用于搜索过滤
    searchQuery: '',   // 搜索关键词
    searchFocused: false // 搜索框是否聚焦
  },
  observers: {
    'show': function(newShow) {
      if (newShow) {
        this.loadBuiltinBooks();
      }
    }
  },
  methods: {
    // 加载内置词书列表
    loadBuiltinBooks: async function() {
      wx.showLoading({ title: '加载词书列表...' });
      try {
        // 从云端获取词书数据
        const books = await getBuiltinBooks();
        
        if (books && books.length > 0) {
          // 存储原始数据和过滤后的数据
          this.setData({
            originalBooks: books,
            builtinBooks: books,
            searchQuery: '' // 重置搜索关键词
          });
        } else {
          // 如果没有获取到数据
          wx.showToast({ title: '获取到词书失败', icon: 'none' });
          this.setData({
            originalBooks: [],
            builtinBooks: [],
            searchQuery: ''
          });
        }
      } catch (e) {
        console.error('加载内置词书异常', e);
        this.setData({
          originalBooks: [],
          builtinBooks: []
        });
      } finally {
        wx.hideLoading();
      }
    },
    
    // 搜索输入处理
    onSearchInput: function(e) {
      const query = e.detail.value.trim();
      this.setData({ searchQuery: query });
      this._filterBooksByQuery(query);
    },
    
    // 搜索框聚焦
    onSearchFocus: function() {
      this.setData({ searchFocused: true });
    },
    
    // 搜索框失焦
    onSearchBlur: function() {
      this.setData({ searchFocused: false });
    },
    
    // 清除搜索
    onClearSearch: function() {
      this.setData({ 
        searchQuery: '',
        builtinBooks: this.data.originalBooks 
      });
    },
    
    // 根据搜索词过滤词书
    _filterBooksByQuery: function(query) {
      if (!query) {
        this.setData({ builtinBooks: this.data.originalBooks });
        return;
      }
      
      // 进行不区分大小写的模糊搜索
      const lowercaseQuery = query.toLowerCase();
      const filteredBooks = this.data.originalBooks.filter(book => 
        book.name.toLowerCase().includes(lowercaseQuery)
      );
      
      this.setData({ builtinBooks: filteredBooks });
    },
    
    // 选择词书
    selectBook: function(e) {
      const { id, name } = e.currentTarget.dataset;
      this.close();
      this.triggerEvent('select', { id, name });
    },
    
    // 关闭模态框
    close: function() {
      // 重置搜索状态
      this.setData({
        searchQuery: '',
        searchFocused: false
      });
      this.triggerEvent('close');
    }
  }
});